package com.nwu.user.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nwu.common.result.Result;
import com.nwu.common.utills.JwtUtil;
import com.nwu.user.domain.Role;
import com.nwu.user.domain.RoleUser;
import com.nwu.user.domain.User;
import com.nwu.user.domain.dto.LoginDto;
import com.nwu.user.domain.po.LoginUser;
import com.nwu.user.domain.vo.LoginVo;
import com.nwu.user.properties.JwtProperties;
import com.nwu.user.service.LoginService;
import com.nwu.user.service.RoleService;
import com.nwu.user.service.RoleUserService;
import com.nwu.user.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/userCom")
@Api(tags = "用户通用接口")
@Slf4j
@RequiredArgsConstructor
public class UserCommonController {
    private final JwtProperties jwtProperties;
    private final LoginService loginService;
    private final UserService userService;
    private final RoleUserService roleUserService;
    private final RoleService roleService;

    @ApiOperation(value = "登录")
    @PostMapping("/login")
    public Result<LoginVo> login(@RequestBody LoginDto loginDto){
        log.info("用户登录：{}",loginDto);
        User user = loginService.login(loginDto);
        //登录成功后，生成jwt令牌
        Map<String,Object> claims = new HashMap<>();
        //放入userid
        claims.put("userId",user.getId());
        //查询权限并且放入权限
        List<String> stringList = userService.selectPermsByUserId(user.getId());
        claims.put("menus",stringList);
        System.out.println(claims.get("menus"));
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);

        LoginVo loginVo = LoginVo.builder()
                .id(user.getId())
                .userName(user.getUsername())
                .name(user.getName())
                .token(token)
                .build();
        return Result.success(loginVo);
    }

    @ApiOperation("获取 用户权限信息")
//    @PreAuthorize("hasAuthority('common')")
    @GetMapping("/userInfo")
    public Result userInfo(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Long id = (Long) authentication.getPrincipal();
        return Result.success(loginService.getRoleById(id));
    }


    @ApiOperation("查询 全部角色")
    @GetMapping("/allRole")
    public Result listRole(){
        LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<Role>()
                .select()
                .ne(Role::getId,1);//管理员
        return Result.success(roleService.list(wrapper));
    }

    @ApiOperation("注册")
    @PostMapping("/register")
    public Result save(@RequestBody User entity,Integer roleId){
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String password = passwordEncoder.encode(entity.getPassword());
        entity.setPassword(password);
        userService.save(entity);
        LambdaQueryWrapper<User>userLambdaQueryWrapper = new LambdaQueryWrapper<User>()
                .select().eq(User::getUsername,entity.getUsername());
        RoleUser roleUser = RoleUser.builder()
                .roleId(roleId)
                .userId(userService.getOne(userLambdaQueryWrapper).getId())
                .build();
        roleUserService.save(roleUser);
        return Result.success();
    }
    @ApiOperation("注销")
//    @PreAuthorize("hasAuthority('common')")
    @DeleteMapping("/unregister")
    public Result delete(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Long id = (Long) authentication.getPrincipal();
        LambdaQueryWrapper<RoleUser> roleUserLambdaQueryWrapper = new LambdaQueryWrapper<RoleUser>()
                .eq(id!=null,RoleUser::getUserId,id);
        roleUserService.remove(roleUserLambdaQueryWrapper);
        userService.removeById(id);
        return Result.success();
    }

    @ApiOperation("修改 个人信息")
    @PutMapping("/mine")
    public Result updateById(@RequestBody User userChange){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Long id = (Long) authentication.getPrincipal();
        userChange.setId(id);
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String password = passwordEncoder.encode(userChange.getPassword());
        userChange.setPassword(password);
        userService.updateById(userChange);
        return Result.success();
    }
    @ApiOperation("查询 个人信息")
    @GetMapping("/mine")
    public Result getById(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Long id = (Long) authentication.getPrincipal();
        return Result.success(userService.getById(id));
    }
}
